// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const userCollection = db.collection('users')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { userInfo } = event
  
  const openId = wxContext.OPENID
  const appId = wxContext.APPID
  const unionId = wxContext.UNIONID
  
  if (!openId) {
    return {
      success: false,
      message: '未获取到用户OpenID'
    }
  }
  
  try {
    // 查询用户是否已存在
    const userRes = await userCollection.where({
      openId: openId
    }).get()
    
    let userId = null
    
    if (userRes.data && userRes.data.length > 0) {
      // 用户已存在，更新信息
      const existingUser = userRes.data[0]
      userId = existingUser._id
      
      await userCollection.doc(userId).update({
        data: {
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          gender: userInfo.gender,
          country: userInfo.country,
          province: userInfo.province,
          city: userInfo.city,
          lastLoginTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })
    } else {
      // 用户不存在，创建新用户
      const result = await userCollection.add({
        data: {
          openId: openId,
          appId: appId,
          unionId: unionId,
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          gender: userInfo.gender,
          country: userInfo.country,
          province: userInfo.province,
          city: userInfo.city,
          createTime: db.serverDate(),
          lastLoginTime: db.serverDate(),
          updateTime: db.serverDate(),
          imageCount: 0  // 用户创作的图片数量
        }
      })
      
      userId = result._id
    }
    
    // 查询最新的用户信息返回
    const updatedUser = await userCollection.doc(userId).get()
    
    return {
      success: true,
      userInfo: {
        ...updatedUser.data,
        _id: updatedUser.data._id.toString() // 转换为字符串便于前端使用
      }
    }
    
  } catch (err) {
    console.error('用户登录/注册失败', err)
    return {
      success: false,
      message: '用户登录/注册失败',
      error: err
    }
  }
} 